<template>
  <div id="tree">
    <div v-for="(item, subscript) in treeArray" :key="item.id">
      <div class="tree-part">
        <span v-if="level > 0" class="perch"
          ><span v-for="index of 2 * level - 1" :key="item.id + '-' + index"
            >├─</span
          >
        </span>

        <a-icon
          :style="`${
            item.hasOwnProperty('children') && item.children.length > 0
              ? 'cursor:pointer'
              : 'opacity:0;cursor:auto'
          }`"
          :type="
            openArray.indexOf(item.id) == -1 ? 'caret-right' : 'caret-down'
          "
          style="font-size: 15px"
          v-on:click="open(item.id, openArray.indexOf(item.id))"
        />

        <span v-show="level > 0">├─</span>
        <a-checkbox
          style="margin-left: 5px"
          :checked="checkedTreeArr.indexOf(item.id) != -1 ? true : false"
          @click="checkedChangeTree(item.id, subscript)"
        >
          {{ item[mapping['name']] }}
        </a-checkbox>
        <div
          v-if="operationChecked.hasOwnProperty(item.id)"
          style="margin-left: 50px"
        >
          <a-checkbox
            :indeterminate="
              operationChecked[item.id].length != item.permission.length &&
              operationChecked[item.id].length > 0
                ? true
                : false
            "
            :checked="
              operationChecked[item.id].length == item.permission.length
            "
            :disabled="checkedTreeArr.indexOf(item.id) == -1 ? true : false"
            @change="onChange($event, item.id)"
          >
            全选
          </a-checkbox>
          <a-divider type="vertical" />
          <a-checkbox-group
            style="margin-left: 20px"
            v-model="operationChecked[item.id]"
            :disabled="checkedTreeArr.indexOf(item.id) == -1 ? true : false"
            :options="item.permission"
            @change="++key"
            :key="key"
          />
        </div>
      </div>

      <div v-show="openArray.indexOf(item.id) != -1">
        <Tree
          :ref="'getTree-' + item.id"
          :treeArray="item.children"
          :level="level + 1"
          :pid="item.id"
          :openArray="openArray"
          :column_id="column_id"
          :permission_id="permission_id"
          :mapping="mapping"
        >
        </Tree>
      </div>
    </div>
  </div>
</template>
<script>
// import CheckBox from "./CheckBox";
export default {
  name: "Tree",
  props: {
    treeArray: Array,
    level: Number,
    openArray: Array,
    pid: Number,
    column_id: Array, //旧选择的栏目id
    permission_id: Array, //旧选择的操作id
    mapping:Object
  },
  components: {},
  data() {
    return {
      checkedTreeArr: [], //已选中的栏目
      checkedTreeAll: [], //全选模板
      key: 0,
      operationChecked: {}, //操作
      operationCheckedMod: {}, //全选的东西存起来
      column_id_tmp: [],
    };
  },
  created() {
    const { treeArray, column_id, permission_id } = this;
    // console.log(column_id.length);
    // console.log(column_id);
    let column_idOld = [];
    let permission_idOld = {};

    // console.log(column_id_tmp);
    if (treeArray) {
      for (let i = 0; i < treeArray.length; i++) {
        this.checkedTreeArr.push(treeArray[i]["id"]);
        if (column_id) {
          //栏目拥有旧数据时
          let indexOf = column_id.indexOf(treeArray[i]["id"].toString());
          if (indexOf != -1) {
            column_idOld.push(treeArray[i]["id"]);
            //  column_id_tmp.splice(indexOf,1)
          }
        }
        if (treeArray[i].hasOwnProperty("permission")) {
          let tmp = [];
          if (!permission_id) {
            tmp = treeArray[i].permission.map((item) => item.value);
          } else {
            let permissionValueOld = []
            for (let j = 0; j < treeArray[i].permission.length; j++) {
              let permissionValue = treeArray[i].permission[j].value;
              tmp.push(permissionValue);
              if(permission_id.indexOf(permissionValue.toString()) != -1 ){
                  permissionValueOld.push(permissionValue)
              }
            }
            permission_idOld[treeArray[i]["id"]]  = permissionValueOld
          }
          this.operationChecked[treeArray[i]["id"]] = tmp;
        }
      }
      this.operationCheckedMod = JSON.parse(
        JSON.stringify(this.operationChecked)
      ); //第一次保存起来 操作id
      this.checkedTreeAll = JSON.parse(JSON.stringify(this.checkedTreeArr)); //第一次保存起来 栏目id
      if (column_id) {                              //拥有旧栏目数据
        this.checkedTreeArr = column_idOld;
      }

      if(permission_id){                     //拥有旧权限数据
          this.operationChecked = permission_idOld;
      }

      // console.log(column_idOld);
      //  if(column_id_tmp && column_id_tmp.length > 0){    //有原数据的情况下
      //       this.checkedTreeArr =  column_idOld
      //       this.column_id_tmp  =  column_id_tmp
      //  }

      // console.log(column_id_tmp);
      // if(this.column_id.length > 0){
      //     this.checkedTreeArr = this.column_id
      // }
      // if(this)
    }
    //   return treeArray;
  }, //生命周期 - 创建完成（可以访问当前this实例）
  mounted() {}, //生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  watch: {},
  computed: {},
  methods: {
    open(id, isOpen) {
      this.$parent.open(id, isOpen);
    },
    clearPid(id = 0) {
      if (id) {
        //第一次进来不做删除返回上级删除
        let indexOf = this.checkedTreeArr.indexOf(id);
        this.checkedTreeArr.splice(indexOf, 1);
      }
      // console.log( this.checkedTreeArr)
      if (this.checkedTreeArr.length == 0 && this.pid != 0) {
        this.$parent.clearPid(this.pid); //清除父级
      }
    },

    checkedPid(id = 0) {
      if (id) {
        for (let i = 0; i < this.treeArray.length; i++) {
          if (this.treeArray[i].id == id) {
            //找出pid
            if (this.checkedTreeArr.indexOf(id) == -1) {
              //判断是否已经选中 不选中则添加
              this.checkedTreeArr.push(id);
            }
            break;
          }
        }
      }
      if (this.pid != 0) {
        this.$parent.checkedPid(this.pid); //全选时继续调用
      }
    },

    checkedChangeTree(id, subscript) {
      let indexOf = this.checkedTreeArr.indexOf(id);
      let subscriptArray = this.treeArray[subscript];

      if (indexOf == -1) {
        //没有时为选中

        this.checkedTreeArr.push(id);
        this.operationRole(id, true); //操作权限
        var operation = true;
        this.checkedPid(); //判断选中父级
      } else {
        //有时为清除

        this.checkedTreeArr.splice(indexOf, 1);

        this.operationRole(id, false); //操作权限

        var operation = false;
        this.clearPid(); //判断清除父级
      }
      if (
        //含有子级时 操作子级
        subscriptArray.hasOwnProperty("children") &&
        subscriptArray.children.length > 0
      ) {
        this.$refs["getTree-" + id][0].operationSon(operation); //清除子级
      }
    },
    /**
     * @description: 操作子级子组件
     * @param  {Boolean} operation  true 为全选子级 false为清空子级
     */
    operationSon(operation) {
      this.checkedTreeArr = operation
        ? JSON.parse(JSON.stringify(this.checkedTreeAll))
        : []; //清空所有子级

      this.operationChecked = operation
        ? JSON.parse(JSON.stringify(this.operationCheckedMod)) //选中所有子级的权限
        : this.forAssembly(this.operationChecked); //清空所有子级的权限

      for (let i = 0; i < this.treeArray.length; i++) {
        let id =
          this.treeArray[i].hasOwnProperty("children") &&
          this.treeArray[i].children.length > 0
            ? this.treeArray[i].id
            : 0;
        if (id) {
          //有子集继续调用子组件的清除
          this.$refs["getTree-" + id][0].operationSon(operation);
        }
      }
    },
    getData() {
      //获取栏目权限最后的数据
      let array = this.checkedTreeArr;
      for (let key in this.$refs) {
        array = [...array, ...this.$refs[key][0].getData()];
      }
      return array;
    },
    getOperation() {
      let operationChecked = this.operationChecked;
      let array = [];
      for (let key in operationChecked) {
        array = [...operationChecked[key], ...array];
      }
      for (let key in this.$refs) {
        array = [...array, ...this.$refs[key][0].getOperation()];
      }
      return array;
    },
    onChange(e, id) {
      //全选按钮
      if (e.target.checked == false) {
        this.operationChecked[id] = [];
      } else {
        //找到id的数组
        this.operationChecked[id] = this.operationCheckedMod[id];
      }
      this.key++;
    },
    /**
     * @description:  操作权限
     * @param  id       栏目id
     * @param  {Boolean} operation  true为权限 false为全空
     * @return {*}
     */
    operationRole(id, operation = false) {
      if (this.operationChecked.hasOwnProperty(id)) {
        this.operationChecked[id] = operation
          ? this.operationCheckedMod[id]
          : [];
      }
    },

    forAssembly(operationChecked) {
      //  console.log(operationChecked);

      for (let key in operationChecked) {
        operationChecked[key] = []; //清空
      }
      return operationChecked;
    },
    mappingFunc(){
      // this.mapping[item]
    }
  },
};
</script>
<style lang="less" scoped>
.tree-part {
  display: flex;
  align-items: center;
  width: 100%;
  // border: 1px solid red;
  // position: relative;
}
.perch {
  opacity: 0;
}
</style>
